package com.wyj.rpc.config;

import com.wyj.rpc.handler.RpcServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;


/**
 * TODO: rpc服务的netty服务端，接收请求、作出处理、返回结果；
 *
 * @author wuyijie
 * @date 2021/12/26 11:23 上午
 */
@Component
public class RpcServer implements DisposableBean {

    EventLoopGroup bossGroup = null;
    EventLoopGroup workerGroup = null;

    public void startServer(String ip, int port) {
        try {
            bossGroup = new NioEventLoopGroup();
            workerGroup = new NioEventLoopGroup();
            ServerBootstrap serverBootstrap = new ServerBootstrap();

            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast(new StringEncoder());
                            pipeline.addLast(new StringDecoder());
                            //todo: 业务处理类
                            pipeline.addLast(new RpcServerHandler());
                        }
                    });
            ChannelFuture channelFuture = serverBootstrap.bind(ip, port).sync();
            registerNettyServer(ip, port);

            System.out.println("=====rpc服务端的netty启动成功====端口为：" + port);
            //同步监听通道关闭事件
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
            if (null != bossGroup) {
                bossGroup.shutdownGracefully();
            }
            if (null != workerGroup) {
                workerGroup.shutdownGracefully();
            }
        }


    }


    @Override
    public void destroy() throws Exception {
        if (null != bossGroup) {
            bossGroup.shutdownGracefully();
        }
        if (null != workerGroup) {
            workerGroup.shutdownGracefully();
        }
    }

    /**
     * TODO: 注册服务端信息到zk
     *
     * @author wuyijie
     * @date 2022/1/6 5:17 PM
     */
    private void registerNettyServer(String ip, int port) {
        //创建zk客户端
        CuratorFramework client = CuratorFrameworkFactory.builder().connectString("server.aliyun:12181")
                .sessionTimeoutMs(5000)
                .connectionTimeoutMs(3000)
                .retryPolicy(new ExponentialBackoffRetry(1000, 5))
                .build();
        client.start();
        final Stat stat;
        try {
            //如果节点不存在，创建临时节点
            String path="/nettyServer/" + ip + ":" + port;
            stat = client.checkExists().forPath(path);
            if (null == stat) {
                //创建临时节点
                client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path, (""+"_"+ LocalDateTime.now().toString()).getBytes(StandardCharsets.UTF_8));
                System.out.println("向zk服务端注册rpc服务端信息成功···");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
